package fi.foyt.cs.actions;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.restlet.Application;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.Form;
import org.restlet.resource.ServerResource;
import org.restlet.routing.Filter;
import org.restlet.routing.Router;

import fi.foyt.cs.actions.friends.AcceptResource;
import fi.foyt.cs.actions.friends.RejectResource;
import fi.foyt.cs.controller.SystemController;
import fi.foyt.cs.persistence.domainmodel.system.ExternalLinkVerificationCode;

public class ActionsApplication extends Application {

  @Override
  public synchronized Restlet createInboundRoot() {

    Router router = new Router(getContext());

    attachResource(router, "/friends/accept", AcceptResource.class, false);
    attachResource(router, "/friends/reject", RejectResource.class, false);

    return router;
  }

  private void attachResource(Router router, String urlTemplate, Class<? extends ServerResource> resource, boolean matchingQuery) {
    LinkVerificationFilter linkVerificationFilter = new LinkVerificationFilter();
    linkVerificationFilter.setNext(resource);
    router.attach(urlTemplate, linkVerificationFilter).setMatchingQuery(matchingQuery);
  }

  private class LinkVerificationFilter extends Filter {

    protected int beforeHandle(Request request, Response response) {
      Form query = request.getOriginalRef().getQueryAsForm();
      String verificationCode = query.getFirstValue("elvc");
      String userIdParam = query.getFirstValue("u");
      // Check if all mandatory parameters are present
      if (!StringUtils.isBlank(verificationCode) && !StringUtils.isBlank(userIdParam)) {
        Long userId = NumberUtils.createLong(userIdParam);
        SystemController systemController = new SystemController();
        // Check if link is valid
        ExternalLinkVerificationCode externalLinkVerificationCode = systemController.findExternalLinkVerificationCodeByVerificationCode(verificationCode);
        if (externalLinkVerificationCode != null && externalLinkVerificationCode.getUserId().equals(userId)) {
          // Link is valid
          return CONTINUE;
        }
      }
      // If some of the conditions are not met request is canceled
      return STOP;
    }
    
    @Override
    protected void afterHandle(Request request, Response response) {
      SystemController systemController = new SystemController();
      Form query = request.getOriginalRef().getQueryAsForm();
      String verificationCode = query.getFirstValue("elvc");
      ExternalLinkVerificationCode externalLinkVerificationCode = systemController.findExternalLinkVerificationCodeByVerificationCode(verificationCode);
      systemController.deleteExternalLinkVerificationCode(externalLinkVerificationCode);
      super.afterHandle(request, response);
    }
  }
}